/*
1天内时分秒组件
times: formdate
mint :倒计时的分钟输
fn: 倒计时完成的回调
*/
import React, { useEffect, useState } from 'react';
const getSeconds = (s) => {
  let second = parseInt(s); // 秒
  let minute = 0;
  let house = 0;
  let date = 0;
  if (second > 60) {
    //如果秒数大于60，将秒数转换成整数
    //获取分钟，除以60取整数，得到整数分钟
    minute = parseInt(second / 60);
    //获取秒数，秒数取佘，得到整数秒数
    second = parseInt(second % 60);
    //秒数
    if (minute > 60) {
      //获取小时，获取分钟除以60，得到整数小时
      house = parseInt(minute / 60);
      //获取小时后取佘的分，获取分钟除以60取佘的分
      minute = parseInt(minute % 60);
    }
    if (house > 24) {
      //获取小时，获取分钟除以24，得到整数小时
      date = parseInt(house / 24);
      //获取小时后取佘的分，获取分钟除以60取佘的分
      house = parseInt(house % 24);
    }
  }
  var result = '';
  if (second >= 0 && second < 10) {
    result = '0' + parseInt(second) + '';
  } else {
    result = '' + parseInt(second) + '';
  }
  if (minute >= 0 && minute < 10) {
    result = '0' + parseInt(minute) + ':' + result;
  } else {
    result = '' + parseInt(minute) + ':' + result;
  }
  if (house >= 0 && house < 10) {
    result = '0' + parseInt(house) + ':' + result;
  } else {
    result = '' + parseInt(house) + ':' + result;
  }
  if (s > 0) {
    return result;
  } else return '';
};

export default (props) => {
  const { times = '', fn, mint = 5, type = 'countdown' } = props;
  let time =
    parseInt(new Date().getTime() / 1000) -
    parseInt(new Date(times.replace(/-/g, '/')).getTime() / 1000);
  const [interVal, setIntervals] = useState(0);
  let i = 0;
  useEffect(() => {
    let controller = true;
    let setTime;
    if (type === 'countdown') {
      setTime = setInterval(() => {
        i++;
        setIntervals(parseInt(mint) * 60 - time - i);
        if (mint * 60 - time === i || controller === false) {
          clearInterval(setTime);
          if (mint * 60 - time === i) {
            fn && fn();
          }
        }
      }, 1000);
    } else {
      setTime = setInterval(() => {
        i++;
        setIntervals(time + i >= 0 ? 0 : Math.abs(time + i));
        if (time + i >= 0 || controller === false) {
          clearInterval(setTime);
          if (time + i >= 0) {
            fn && fn();
          }
        }
      }, 1000);
    }
    return () => {
      controller = false;
      clearInterval(setTime);
    };
  }, []);
  return <>{getSeconds(interVal)}</>;
};
